﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace RabbitMQDemo.Consumer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start consumers");

            var connFactory = new ConnectionFactory
            {
                HostName = "106.53.127.56",
                Port = 5672,
                UserName = "rabbitmqdemo",
                Password = "rabbitmqdemo@test",
                VirtualHost = "rabbitmqdemo",

            };
            using (var conn = connFactory.CreateConnection())
            {
                using (var channel = conn.CreateModel())
                {
                    //死信交换机和死信队列
                    var dlxExchangeName = "dlx_exchange";
                    channel.ExchangeDeclare(exchange: dlxExchangeName, type: "fanout", durable: false, autoDelete: false, arguments: null);
                    var dlxQueueName = "dlx_queue";
                    channel.QueueDeclare(queue: dlxQueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueBind(queue: dlxQueueName, exchange: dlxExchangeName, routingKey: "");

                    var queueName = "nackorreject_queue";
                    var arguments = new Dictionary<string, object>
                    {
                        { "x-dead-letter-exchange", dlxExchangeName }
                    };
                    channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: arguments);
                    channel.BasicQos(0, 5, false);

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var message = ea.Body;
                        Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message.ToArray()));

                        if (Encoding.UTF8.GetString(message.ToArray()).Contains("50"))
                        {
                            Console.WriteLine("拒收");
                            ((EventingBasicConsumer)model).Model.BasicReject(ea.DeliveryTag, requeue: false);//关键在于requeue=false
                            return;
                        }

                        ((EventingBasicConsumer)model).Model.BasicAck(ea.DeliveryTag, multiple: false);
                    };

                    channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
                    Console.ReadKey();
                }
            }
        }
    }
}